#!/usr/bin/python
# coding=utf-8


__author__ = 'LCD'


import re


def read_demo_index_html(path):
    path = path.rstrip()

    try:
        with open(path, 'r') as fp:
            html = fp.read()
            # print(html)
    except FileNotFoundError as e:
        raise FileNotFoundError('html文件未找到，请检查路径')
    except Exception as e:
        raise Exception('html文件读取失败，原因：{}'.format(e))

    else:
        return html

def read_ttf_name(html):
    try:
        pattern = re.compile(r'<p>"(.*?)" 是你项目下的 font-family。可以通过编辑项目查看，默认是 "iconfont"。</p>', re.S)
        basic_content = re.finditer(pattern, html)

        for match in basic_content:
            d = re.match(
                r'<p>"(.*?)" 是你项目下的 font-family。可以通过编辑项目查看，默认是 "iconfont"。</p>',
                match.group(), re.S)
            return d.group(1)

    except Exception as e:
        raise Exception('html解析失败')

    else:
        pass


def read_name_code(html):
    try:
        # 获取所需内容
        pattern = re.compile(r'<span class="icon (.*?)<div class="code-name">&amp;',
                             re.S)
        # 过滤，得到满足条件的内容
        basic_content = re.finditer(pattern, html)

        # 对内容进行加工，得到自己想要的内容
        arr = []
        for match in basic_content:
            dic = {}

            # 使用match方法匹配整个子串
            d = re.match(
                r"""<span class="icon (.*?)">&#x(.*?);</span>
                <div class="name">(.*?)</div>""",
                match.group(), re.S)

            dic['font'] = d.group(1)

            # 直接使用字符串前缀'\u'与十六进制字符结合创建Unicode字符串
            code_str = chr(int(d.group(2), 16))

            dic['code'] = code_str
            dic['name'] = d.group(3)

            arr.append(dic)

    except Exception as e:
        raise Exception('html解析失败')

    else:
        # 返回结果列表
        return arr


def make_arr_name(lst):
    names = []
    for i in range(len(lst)):
        name = lst[i]['name']
        arr = name.split(' ')
        name = '_'.join(arr)
        arr = name.split('-')
        name = '_'.join(arr)

        if name in names:
            name += f'_{i}'

        names.append(name)
        lst[i]['name'] = name

    return lst


def make_swift(path_output, classname, arr, pod_key):
    first = arr[0]
    # 头部
    swift = """
    //更多代码自动化可了解 :https://gitee.com/CaamDau/SapSapSeoi
    
    import Foundation
    import UIKit
    import CaamDau
    
    public enum %s {
        class Help {}
    """ % classname

    # enum
    for item in arr:
        swift += """
        case t%s(_ size:CGFloat)""" % item['name']

    swift += """
    }
    """

    # CD_IconFontProtocol
    swift += """
    extension %s:CD_IconFontProtocol{
        public var font:UIFont {
            return UIFont.iconFont("%s", size: self.size, forClass: %s.Help.self, from: "%s")
        }
        """ % (classname, first['font'], classname,  pod_key)


    swift += """
        public var size: CGFloat {
            switch self {
            case """

    for i in range(len(arr)):
        if i == len(arr)-1:
            swift += """.t%s(let size):
                return size
            }
        }
                    """ % arr[i]['name']
        else:
            swift += """.t%s(let size),
            """ % arr[i]['name']

    swift += """
        public var text: String {
            switch self {"""

    for item in arr:
        swift += """ 
            case .t%s:
                return "%s" """ % (item['name'], item['code'])

    swift += """
            }
        }
    }
    """

    try:
        path = path_output.rstrip()
        file = path + "/" + classname + '.swift'
        with open(file, 'w') as f:
            f.write(swift)
    except Exception as e:
        raise Exception('Swift文件写入错误，请检查路径')


def make_android(path_output, file_name, arr):
    text = """
    <!--iconfont 更多代码自动化可了解 :https://gitee.com/CaamDau/SapSapSeoi-->
    <resources>
    """
    for item in arr:
        text += """<string name="iconfont_%s">%s</string>
        """ % (item['name'], item['code'])

    text += """
    </resources>
    """
    try:
        path = path_output.rstrip()
        file = path + "/strings_iconfont.xml"
        with open(file, 'w') as f:
            f.write(text)
    except Exception as e:
        raise Exception('文件写入错误，请检查路径')

    # 构建kotlin文件

    text = """
    @file:JvmName("IconFontUtils")
    package com.towork.iconfont
    
    import android.content.Context
    import android.graphics.Typeface
    import android.widget.TextView
    import com.towork.json.JSON
    import com.towork.utils.stringR
    import com.towork.works.R
    
    
    fun TextView.iconfont(context: Context, font:IconFont.Font){
        this.iconfont(context, font.code)
    }
    fun TextView.iconfont(context: Context, code:String){
        this.typeface = Typeface.createFromAsset(context.assets, "iconfont.ttf")
        this.text = code
    }
    
    <!--iconfont 更多代码自动化可了解 :https://gitee.com/CaamDau/SapSapSeoi-->
    object IconFont {
        class Font(val name:String, val code:String){}
        
    """
    for item in arr:
        text += """@JvmField val i_%s:Font = Font("%s",R.string.iconfont_%s.stringR)
        """ % (item['name'], item['name'], item['name'])

    text += """
        }
        """
    try:
        path = path_output.rstrip()
        file = path + "/" + file_name + ".kt"
        with open(file, 'w') as f:
            f.write(text)
    except Exception as e:
        raise Exception('文件写入错误，请检查路径')

def setup():
    print("\n========== 进入程序将iconfont文件输出iOS/Android/HarmonyOS格式文件 ==========")
    path_input = input("请输入你的iconfont ~_demo_index.html 的路径：")
    path_output = input("请输入你的iconfont ~.xxx 保存的路径：")
    file_name = input("请输入你的iconfont类 ~.xxx 的文件名：")
    key_pod = input("如果你使用pod管理该iconfont，请输入你的resource_bundles Key，否则无需输入：")
    # cd_import = raw_input("默认将需要引入 CD 组件，你是否需要：")

    try:
        html = read_demo_index_html(path_input)
        arr = make_arr_name(read_name_code(html))
        make_swift(path_output, file_name, arr, key_pod)
        make_android(path_output, file_name, arr)
    except Exception as e:
        print(e)
        setup()
    else:
        print('已完成')
        next = input("是否继续创建(Y/N)：")
        if next.lower() == "y":
            setup()


if __name__ == '__main__':
    setup()
    # /Users/caamdau/Downloads/iconfont/demo_index.html